#!/usr/bin/python
# -*- coding: utf-8 -*-
# File: cloud.py
# Author: Tomás Vírseda
# License: GPL v3
# Description: a cloud widget

import gtk
import gtk.gdk
import pango
from math import *

class Cloud(gtk.Table):
    def __init__(self, qname, data, func=None, nrows=None, ncols=None, homogeneous=False):
        gtk.Table.__init__(self)

        if not data:
            return

        if not func:
            self.func = self.myfunc

        if not nrows or not ncols:
            n = int(ceil(sqrt(len(data))))
            if n > 4:
                ncols = 4
                nrows = len(data) - ncols
            else:
                nrows = ncols = n

        self.data = self._sortedDictValues(data)
        self.qname = qname
        self.func = func
        self.nrows = nrows
        self.ncols = ncols
        self.max_frequency = 0

        self.add_events(gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON1_MOTION_MASK)
        self.resize(self.nrows, self.ncols)
        self._get_max_frequency()
        self._proccess_data()
        self.show_all()

    def _sortedDictValues(self, adict):
        """
        http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52306
        """
        items = adict.items()
        items.sort()

        #return [value for key, value in items]
        return items

    def _get_max_frequency(self):
        for tag, freq in self.data:
            if freq > self.max_frequency:
                self.max_frequency = freq

    def _get_font_size(self, label, frequency):
        proportion = int((frequency * 100) / self.max_frequency)
        size = 7

        if proportion < 10:
            size = 7
        elif (proportion in range(10, 19)):
            size = 7
        elif (proportion in range(20, 29)):
            size = 7
        elif (proportion in range(30, 39)):
            size = 8
        elif (proportion in range(40, 49)):
            size = 9
        elif (proportion in range(50, 59)):
            size = 10
        elif (proportion in range(60, 69)):
            size = 10
        elif (proportion in range(70, 79)):
            size = 11
        elif (proportion in range(80, 89)):
            size = 12
        elif (proportion in range(90, 99)):
            size = 12
        elif proportion == 100:
            size = 12

        #print "label(%20s)\tfrequency(%5d)\tproportion(%3d)\t\tfont-size(%2d)" % (label, frequency, proportion, size)
        return size

    def _make_button(self, tag):
        button = gtk.Button()
        label = tag[0]
        frequency = tag[1]
        # Set tag label into the button
        button.set_label(label)
        # Set font size according to frequency
        size = self._get_font_size(label, frequency)
        font = "Arial %d" % size

        if button.get_use_stock():
            label = button.child.get_children()[1]
        elif isinstance(button.child, gtk.Label):
            label = button.child
        else:
            return ValueError("button does not have a label")

        label.modify_font(pango.FontDescription(font))
        button.set_relief(gtk.RELIEF_NONE)

        return button

    def _proccess_data(self):
        e = 0 # elements
        i = 0 # row counter
        j = 0 # column counter
        tooltips = gtk.Tooltips()
        max_data = self.nrows * self.ncols

        if (len(self.data) < max_data):
            max_data = len(self.data) - 1
        for i in range(self.nrows):
            for j in range(self.ncols):
                if (e <= max_data):
                    tag = self.data[e]
                    tip = str(tag[1])
                    button = self._make_button(tag)
                    button.set_data("property", self.qname)
                    button.connect("clicked", self.func, tag[0])
                    tooltips.set_tip(button, tip)
                    self.attach(button, i, i+1, j, j+1, gtk.EXPAND, gtk.SHRINK)
                    e = e + 1

    def button_clicked(self, widget, data=None):
        pass

    def myfunc(self, widget, data=None):
        pass

class CloudVazaar(Cloud):
    def button_clicked(self, widget, data=None):
        if not data:
            return None

        #print data

def hola(*args):
    print 'Hola'

def main():
    data =  {}
    data['dublincore'] = 15
    data['rdflib'] = 34
    data['semantic web'] = 51
    data['rdf'] = 5
    window = gtk.Window()
    cloud = CloudVazaar('fookey', data, hola)
    """
    cloud = self.gui.ask.make_report()
    for ns in cloud:
        print ns
        for predicate in cloud[ns]:
            print "\t", predicate
            for data in cloud[ns][predicate]:
                print "\t\t",data, cloud[ns][predicate][data]
    """
    window.add(cloud)
    window.connect("destroy", gtk.main_quit)
    window.show_all()

    gtk.main()

if __name__ == "__main__":
    main()
